import api from "@/api";
import jWeixin from "weixin-js-sdk";
import { checkBrowersIsWechat } from "@/utils";
import tool from "@/utils/tool";
const useWxJSSDK = () => {
	const jsApiList: Array<any> = [
		"updateAppMessageShareData",
		"updateTimelineShareData",
		"hideMenuItems",
		"scanQRCode",
		"openLocation",
		"getLocation",
		"openAddress",
	];
	let _initReady = false;
	let setTimeoutNb = 0;
	// 获取微信配置信息
	const init = () => {
		return new Promise(async (resolve, reject) => {
			let url = window.location.href;
			if ((window as any).__wxjs_is_wkwebview === true) {
				url = tool.get("REDIRECT_URL");
			}
			const { code, data } = await api.system.getJsSDKAtuh.get({ url });
			if (code === 1) {
				const { appId, timestamp, nonceStr, signature } = data;
				jWeixin.config({
					debug: false,
					appId,
					timestamp,
					nonceStr,
					signature,
					jsApiList,
				});
				jWeixin.ready(function () {
					_initReady = true;
				});
				jWeixin.error(function (res) {
					console.log(res);
				});
				resolve({});
			}
		});
	};

	const setShare = async ({
		toPath = "",
		query = {},
		title = "万言国学",
		desc = "结缘立明堂，人生更辉煌",
		imgUrl = "https://bweb.yingfeiwangluo.com/static/images/logo.png",
	}) => {
		if (checkBrowersIsWechat()) {
			if (_initReady) {
				let link = toPath || uni.$u.page();
				const buildData = () => {
					return {
						...query,
					};
				};
				link = `${location.origin}${link}${uni.$u.queryParams(
					buildData()
				)}`;
				jWeixin.hideMenuItems({
					menuList: ["menuItem:copyUrl"],
				});
				jWeixin.updateAppMessageShareData({
					title, // 分享标题
					desc, // 分享描述
					link,
					imgUrl: imgUrl, // 分享图标
					success: function () {},
				});
				jWeixin.updateTimelineShareData({
					title, // 分享标题
					link, // 分享链接
					imgUrl: imgUrl, // 分享图标
					success: function () {},
				});
			} else {
				setTimeoutNb = setTimeoutNb + 1;
				if (setTimeoutNb < 6) {
					await init();
					setTimeout(() => {
						setShare({ toPath, query, title, desc, imgUrl });
					}, 1000);
				}
			}
		}
	};
	interface IgetLocation extends jWeixin.IgetLocation {
		success: (res: {
			latitude: number; // 纬度，浮点数，范围为90 ~ -90
			longitude: number; // 经度，浮点数，范围为180 ~ -180。
			speed: number; // 速度，以米/每秒计
			accuracy: number; // 位置精度
			errMsg: string; // 调用结果
		}) => void;
	}
	const getLocation = async (options: IgetLocation) => {
		if (checkBrowersIsWechat()) {
			if (_initReady) {
				jWeixin.getLocation(options);
			} else {
				setTimeoutNb = setTimeoutNb + 1;
				if (setTimeoutNb < 6) {
					await init();
					setTimeout(() => {
						getLocation(options);
					}, 1000);
				}
			}
		}
	};
	interface IscanQRCode extends jWeixin.IscanQRCode {
		success: (res: {
			resultStr: string; // 当needResult 为 1 时，扫码返回的结果
			errMsg: string; // 调用结果
		}) => void;
	}
	const scanQRCode = async (options: IscanQRCode) => {
		if (checkBrowersIsWechat()) {
			if (_initReady) {
				jWeixin.scanQRCode(options);
			} else {
				setTimeoutNb = setTimeoutNb + 1;
				if (setTimeoutNb < 6) {
					await init();
					setTimeout(() => {
						scanQRCode(options);
					});
				}
			}
		}
	};
	const openAddress = async (options: any) => {
		if (checkBrowersIsWechat()) {
			if (_initReady) {
				jWeixin.openAddress(options);
			} else {
				setTimeoutNb = setTimeoutNb + 1;
				if (setTimeoutNb < 6) {
					await init();
					setTimeout(() => {
						openAddress(options);
					});
				}
			}
		}
	};
	init();
	return { setShare, getLocation, scanQRCode, openAddress };
};
export { useWxJSSDK };
export default useWxJSSDK;
